package com.vrv.netmgr.alarm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.common.util.JsonUtil;
import com.vrv.netmgr.R;
import com.vrv.netmgr.alarm.detail.DetailEquipmentChangedActivity;
import com.vrv.netmgr.vo.ErrorMessage;

/**
 * 设备信息查询中：设备变化
 *
 * @author zxb
 *
 */
public class EquipmentChangedQryActivity extends Activity {

    private static final String TAG = EquipmentChangedQryActivity.class.getSimpleName();
    private static final boolean DEBUG = true && GlobalConstants.DEBUG;
    /** 数据list */
    private ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String, Object>>();
    /** 数据view */
    private ListView listView;
    /** 适配器 */
    private ListAdapter adapter = new ListAdapter();
    /** 总记录数 */
    public int RECORD_COUNT;
    /** 当前页号 */
    public int CUR_INDEX;
    /**
     * 等待对话框
     */
    private ProgressDialog progressDialog;
    // 通过点击按钮查询标记
    private boolean qryByBtnFlag = false;
    // 列表的页脚视图
    private View loadMoreView;
    // 异常判断标记
    private boolean retVal;
    /**
     * 查询
     */
    private static final int BACK_NULL = 2;
    private static final int QUERY = 3;
    /** 查询失败 */
    private static final int NET_ERR = 4;
    private static final int QUERY_BY_IP = 5;

    // /**显示字段*/
    // private String eqmc_deptName;
    // private String eqmc_officeName;
    // private String eqmc_userName;
    // private String eqmc_tel;
    // private String eqmc_ipaddres;
    // private String eqmc_deviceName;
    // private String eqmc_ipaddres1;
    // private String eqmc_errorMsg;
    // private String eqmc_sysUserName;
    // private String eqmc_errorTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.assets_list_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        //
        init();
        bindUI();
        bindListener();
        //
        progressDialog = ProgressDialog.show(EquipmentChangedQryActivity.this, "", "查询中...", true, true);
        /** 开始查询数据 */
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDataFromServer(0, false, null);
                /** 返回数据成功消息 */
                if (!retVal){
                    handler.sendEmptyMessage(NET_ERR);
                }else{
                    if (null == listData || 0 == listData.size()) {
                        handler.sendEmptyMessage(BACK_NULL);
                    } else {
                        handler.sendEmptyMessage(QUERY);
                    }
                }
            }
        }).start();
    }

    /**listview背景设置*/
    private LinearLayout listBackView;
    
    /**
     * 处理器
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            progressDialog.dismiss();
            switch (msg.what) {
            case QUERY:
                fillListView();
                /** listview背景设置 */
                listBackView.setVisibility(listView.getVisibility());
                break;
            case QUERY_BY_IP:
                qryByBtnFlag = true;
                if (RECORD_COUNT > 0) {
                    listView.removeFooterView(loadMoreView);
                    listView.setVisibility(View.VISIBLE);
                    if (RECORD_COUNT > ListViewUtil.PAGESIZE) {
                        String deviceIP = msg.getData().getString("deviceIP");
                        loadMorePage(true, deviceIP);
                    }
                    initializeAdapter();
                    adapter.notifyDataSetChanged();
                } else
                    listView.setVisibility(View.GONE);
                /** listview背景设置 */
                listBackView.setVisibility(listView.getVisibility());
                break;
            case NET_ERR:
                Toast.makeText(EquipmentChangedQryActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
                onBackPressed();
                break;
            case BACK_NULL:
                Toast.makeText(EquipmentChangedQryActivity.this, "数据为空", Toast.LENGTH_LONG).show();
                onBackPressed();
                break;
            }
        }
    };

    /** 标题 */
    TextView tv_title;
    /** 返回按钮 */
    ImageButton imgbtn_back;

    /**
     * 初始化UI
     */
    public void bindUI() {
        tv_title = (TextView) findViewById(R.id.title_text);
        tv_title.setText("设备变化");
        //
        // listView = (ListView) findViewById(R.id.assets_lv_id);
    }

    /**
     * 绑定监听事件
     */
    public void bindListener() {
        imgbtn_back = (ImageButton) findViewById(R.id.backBtn);
        imgbtn_back.setVisibility(View.VISIBLE);
        imgbtn_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //
        // listView.setOnItemClickListener(new ListViewItemClick());
    }

    /** url链接 */
    private String mUrlPrefix;

    private void initUrlPrefix() {
        UrlPrefix urlPrefix = new UrlPrefix(this);
        mUrlPrefix = urlPrefix.getUrlPrefix();
    }

    /**
     * 数据初始化
     */
    private void init() {
        initUrlPrefix();
        
        listBackView = (LinearLayout) findViewById(R.id.list_background);
    }

    /**
     * 查询服务器操作
     *
     * @param map
     * @return
     */
    public boolean query(Map<String, String> map) {
        boolean retVal = false;
        //
        HttpClientToServer httpClientToServer = new HttpClientToServer();

        String urlAddr = mUrlPrefix + "/" + "errorMessage" + "/" + "jsonList.do?errorType=1";

        //
        String response = httpClientToServer.doPost(urlAddr, map);
        if (DEBUG)
            Log.i(TAG, "******* response = " + response);
        //
        if (HttpClientToServer.DO_POST_ERR.equals(response) || HttpClientToServer.DO_POST_EXCEPT.equals(response)) {
            return retVal;
        }
        //
        try {
            JSONTokener jsonParser = new JSONTokener(response);
            JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
            retVal = jsonObj.getBoolean("success");
            if (DEBUG)
                Log.i(TAG, "******* retVal = " + retVal);
            //
            if (!retVal) {
                return retVal;
            }
            //
            int count = jsonObj.getInt("totalRecords");
            if (DEBUG)
                Log.i(TAG, "******* count = " + count);
            RECORD_COUNT = count;
            //
            if (count <= 0) {
                return retVal;
            }
            //
            JSONArray jArr = jsonObj.getJSONArray("records");
            int jArrLen = jArr.length();
            if (DEBUG)
                Log.i(TAG, "******* jArrLen = " + jArrLen);
            //
            if (jArrLen > 0) {
                CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));
                if (DEBUG)
                    Log.i(TAG, "******* CUR_INDEX = " + CUR_INDEX);
            }
            //
            for (int i = 0; i < jArr.length(); i++) {
                JSONObject jObj = (JSONObject) jArr.opt(i);
                //
                HashMap<String, Object> data = new HashMap<String, Object>();
                //
                data.put("eqmc_deptName", JsonUtil.getJsonString(jObj, "deptName"));
                data.put("eqmc_officeName", JsonUtil.getJsonString(jObj, "officeName"));
                data.put("eqmc_userName", JsonUtil.getJsonString(jObj, "userName"));
                data.put("eqmc_tel", JsonUtil.getJsonString(jObj, "tel"));
                data.put("eqmc_ipaddres", JsonUtil.getJsonString(jObj, "ipaddress"));
                data.put("eqmc_deviceName", JsonUtil.getJsonString(jObj, "deviceName"));
                data.put("eqmc_ipaddres1", JsonUtil.getJsonString(jObj, "ipaddress1"));
                data.put("eqmc_errorMsg", JsonUtil.getJsonString(jObj, "errorMsg"));
                data.put("eqmc_sysUserName", JsonUtil.getJsonString(jObj, "sysUserName"));
                data.put("eqmc_errorTime", JsonUtil.getJsonString(jObj, "errorTime"));
                data.put("eqmc_macAddress", JsonUtil.getJsonString(jObj, "macAddress"));
                data.put("eqmc_lookFlag", JsonUtil.getJsonString(jObj, "lookFlag"));
                //
                listData.add(data);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //
        return retVal;
    }

    /**
     * 初始化ListView的适配器
     */
    public void initializeAdapter() {
        for (int i = 0; i < listData.size(); i++) {
            adapter.addItem(listData.get(i));
        }
    }

    /**
     * 加载更多数据
     *
     * @param pageDown
     *            ture 下一页 false 上一页
     */
    private void loadMoreData(boolean pageDown, boolean byDeviceIP, String deviceIP) {
        int index;
        //
        if (pageDown) {
            index = CUR_INDEX + 1;
        } else {
            index = CUR_INDEX - 1;
        }
        //
        listData.clear();
        adapter.clear();
        /** 查询数据 */
        getDataFromServer(index, byDeviceIP, deviceIP);
        //
        int datasize = listData.size();
        //
        for (int i = 0; i < datasize; i++) {
            adapter.addItem(listData.get(i));
        }
    }

    /**
     * 加载更多UI处理
     */
    public void loadMorePage(final boolean byDeviceIP, final String deviceIP) {
        final View loadMoreView = getLayoutInflater().inflate(R.layout.list_page_load, null);
        final Button loadNextButton = (Button) loadMoreView.findViewById(R.id.loadNextButton);
        final Button loadPreButton = (Button) loadMoreView.findViewById(R.id.loadPreButton);
        /** 下一页 */
        loadNextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loadNextButton.getText().equals("查看下一页")) {
                    loadNextButton.setText("正在加载中..."); // 设置按钮文字
                    loadNextButton.setEnabled(false);
                    //
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadMoreData(true, byDeviceIP, deviceIP);
                            /** 更新UI */
                            adapter.notifyDataSetChanged();
                            loadNextButton.setText("查看下一页"); // 恢复按钮文字
                            if ((CUR_INDEX + 1) * ListViewUtil.PAGESIZE >= RECORD_COUNT) {
                                loadNextButton.setVisibility(View.GONE);
                            }
                            if (CUR_INDEX == 1) {
                                loadPreButton.setVisibility(View.VISIBLE);
                            }
                            loadNextButton.setEnabled(true);
                        }
                    }, 0);
                }
            }
        });
        /** 上一页 */
        loadPreButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loadPreButton.getText().equals("查看上一页")) {
                    loadPreButton.setText("正在加载中..."); // 设置按钮文字
                    loadPreButton.setEnabled(false);
                    //
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            loadMoreData(false, byDeviceIP, deviceIP);
                            /** 更新UI */
                            adapter.notifyDataSetChanged();
                            loadPreButton.setText("查看上一页"); // 恢复按钮文字
                            if (CUR_INDEX == 0) {
                                loadPreButton.setVisibility(View.GONE);
                            }
                            if ((CUR_INDEX + 2) * ListViewUtil.PAGESIZE >= RECORD_COUNT) {
                                loadNextButton.setVisibility(View.VISIBLE);
                            }
                            loadPreButton.setEnabled(true);
                        }
                    }, 0);
                }
            }
        });
        /** 设置列表底部视图 */
        listView.addFooterView(loadMoreView);
    }

    /**
     * 查询所有数据
     *
     * @param pageNum
     */
    public void getDataFromServer(int pageNum, boolean byDeviceIP, String deviceIP) {
        if (DEBUG)
            Log.v(TAG, "getDataFromServer()");

        /** 查询条件 */
        Map<String, String> map = new HashMap<String, String>();
        /** Map<String, Object> map = new HashMap<String, Object>(); */

        map.put(GlobalConstants.PAGE_NUM, pageNum + "");
        map.put(GlobalConstants.REG_ASSETS, GlobalConstants.ASSETS_REGISTERED + "");
        if (byDeviceIP)
            map.put("ipaddress1", deviceIP);
        /** 查询结果 */
        retVal = query(map);
    }

    public void fillListView() {
        if (listView == null) {
            // 搜索输入框
            EditText edit = (EditText) findViewById(R.id.assets_conditionQry);
            // 搜索按钮
            ImageView search_btn = (ImageView) findViewById(R.id.search_go_btn);
            edit.setHint(R.string.input_device_ip);

            // /**查询条件添加事件*/
            // edit.addTextChangedListener(new MyTextWatcher(edit, search_btn));
            /** 查询按钮添加事件 */
            search_btn.setOnClickListener(new ClickSearchBtnListener(edit, search_btn));

            listView = (ListView) findViewById(R.id.assets_lv_id);
        }
        if (RECORD_COUNT > 0) {
            listView.removeFooterView(loadMoreView);
            listView.setVisibility(View.VISIBLE);
            if (RECORD_COUNT > ListViewUtil.PAGESIZE)
                loadMorePage(false, null);
            initializeAdapter();
            if (listView.getAdapter() == null)
                listView.setAdapter(adapter);
            else
                adapter.notifyDataSetChanged();
            listView.setOnItemClickListener(new ListViewItemClick());
        }
    }

    /**
     * 查询按钮事件处理
     *
     * @author zxb
     *
     */
    private class ClickSearchBtnListener implements View.OnClickListener {
        EditText edit;
        ImageView search_btn;

        ClickSearchBtnListener(EditText edit, ImageView search_btn) {
            this.edit = edit;
            this.search_btn = search_btn;
        }

        @Override
        public void onClick(View v) {
            final String editVal = edit.getText().toString();
            listData.clear();
            adapter.clear();
            progressDialog = ProgressDialog.show(EquipmentChangedQryActivity.this, "", "查询中...", true, true);
            search_btn.setEnabled(false);
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    getDataFromServer(0, true, editVal);
                    Message msg = new Message();
                    msg.what = QUERY_BY_IP;
                    Bundle data = new Bundle();
                    data.putString("deviceIP", editVal);
                    msg.setData(data);
                    handler.sendMessage(msg);
                    search_btn.setEnabled(true);
                }
            });
        }
    }

    /**
     * item事件
     *
     * @author zxb
     *
     */
    private class ListViewItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            if (DEBUG)
                Log.v(TAG, "ListViewItemClick.onItemClick()");

            HashMap<String, Object> hashMap = adapter.getData(arg2);

            ErrorMessage errorMessage = new ErrorMessage();

            errorMessage.setEqmc_deptName(hashMap.get("eqmc_deptName").toString());
            errorMessage.setEqmc_officeName(hashMap.get("eqmc_officeName").toString());
            errorMessage.setEqmc_userName(hashMap.get("eqmc_userName").toString());
            errorMessage.setEqmc_tel(hashMap.get("eqmc_tel").toString());
            errorMessage.setEqmc_ipaddres(hashMap.get("eqmc_ipaddres").toString());
            errorMessage.setEqmc_deviceName(hashMap.get("eqmc_deviceName").toString());
            errorMessage.setEqmc_ipaddres1(hashMap.get("eqmc_ipaddres1").toString());
            errorMessage.setEqmc_errorMsg(hashMap.get("eqmc_errorMsg").toString());
            errorMessage.setEqmc_sysUserName(hashMap.get("eqmc_sysUserName").toString());
            errorMessage.setEqmc_errorTime(hashMap.get("eqmc_errorTime").toString());
            errorMessage.setEqmc_macAddress(hashMap.get("eqmc_macAddress").toString());
            errorMessage.setEqmc_lookFlag(hashMap.get("eqmc_lookFlag").toString());

            Intent intent = new Intent(EquipmentChangedQryActivity.this, DetailEquipmentChangedActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("info", errorMessage);
            intent.putExtras(bundle);
            startActivity(intent);
        }

    }

    /**
     * 继承工具类适配器
     *
     * @author zxb
     *
     */
    private class ListAdapter extends ListViewAdapter {
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            /** getItem */
            final HashMap<String, Object> hashMap = getData(position);
            if (view == null) {
                view = LayoutInflater.from(EquipmentChangedQryActivity.this).inflate(R.layout.equipmentchange_listpage_item, null);
            }
            /** 默认背景色设置 */
            view.setBackgroundResource(R.drawable.list_item_state1);
            /** 双行背景色设置 */
            if (position % 2 == 0) {
                view.setBackgroundResource(R.drawable.list_item_state);
            }
            //
            TextView eqmc_ipaddres = (TextView) view.findViewById(R.id.eqmc_ipaddres);
            TextView eqmc_deviceName = (TextView) view.findViewById(R.id.eqmc_deviceName);
            TextView eqmc_errorMsg = (TextView) view.findViewById(R.id.eqmc_errorMsg);
            eqmc_ipaddres.setText(hashMap.get("eqmc_ipaddres").toString());
            eqmc_deviceName.setText(hashMap.get("eqmc_deviceName").toString());
            eqmc_errorMsg.setText(hashMap.get("eqmc_errorMsg").toString());
            //
            return view;
        }
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
        super.onBackPressed();
    }
}
